package com.example.leero.graduation;

import android.app.Application;

import com.example.leero.graduation.Util.GsonUtil;
import com.example.leero.graduation.Util.LogUtil;
import com.example.leero.graduation.Util.PreferenceUtil;
import com.example.leero.graduation.Util.StringUtil;
import com.example.leero.graduation.model.User;
import com.tencent.bugly.crashreport.CrashReport;

/**
 * Created by Leero on 2017-5-6.
 */

public class App extends Application {
    public static App mInstance;
    private static User sUser;
    private static String userPhone;
    private static boolean isLogin;

    @Override
    public void onCreate() {

        super.onCreate();

        mInstance = this;
        init();

        // 异常收集
        CrashReport.initCrashReport(getApplicationContext(), "e7e023cc3a", false);
    }

    private void init() {
        if (BuildConfig.DEBUG) {
            LogUtil.setShow(true);
        }

        initUser();
    }


    public static App getInstance() {

        return mInstance;
    }


    private void initUser() {
        String userJson = PreferenceUtil.getString(Constants.USER);
        isLogin = StringUtil.isNotEmpty(userJson);
        if (isLogin) {
            sUser = GsonUtil.fromJson(userJson, User.class);
        }
    }

    public static User getLoginUser() {
        return sUser;
    }

    public static void login(User user) {
        sUser = user;
        userPhone = user.phone;
        String userJson = GsonUtil.toJson(user);
        PreferenceUtil.put(Constants.USER, userJson);
        isLogin = true;
    }

    public static void updateUser(User user) {
        if (isLogin) {
            sUser = user;
            String userJson = GsonUtil.toJson(user);
            PreferenceUtil.put(Constants.USER, userJson);
        }
    }

    public static void logout() {
        PreferenceUtil.put(Constants.USER, "");
        isLogin = false;
        sUser = null;
    }

    public static boolean isLogin() {
        return isLogin;
    }

    public static String getUserPhone () {
        return userPhone;
    }

}
